/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package procesos;

import entidades.Ejercicio;
import entidades.Test;
import java.beans.PropertyVetoException;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

/**
 *
 * @author Oswl_C
 */
public class RealizarEjercicio extends javax.swing.JInternalFrame {

    private Ejercicio ejercicio;
    private int indice;
    private int segundos;
    private int minudos;
    private String textoDeEjercicio;

    /**
     * Creates new form RealizarEjercicio
     */
    public RealizarEjercicio() {
        initComponents();
    }

    RealizarEjercicio(Ejercicio ejericio) {
        initComponents();
        this.ejercicio = ejericio;
        this.lblTit.setText(ejericio.getEjeTitulo());
        this.lblDescri.setText(ejericio.getEjeDescri());
        ejecutarEjercicio();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("lecturadb?zeroDateTimeBehavior=convertToNullPU").createEntityManager();
        itemEjercicioQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT i FROM ItemEjercicio i");
        itemEjercicioList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : itemEjercicioQuery.getResultList();
        lblTit = new javax.swing.JLabel();
        lblDescri = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        lblReloj = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtItemEjer = new javax.swing.JTextPane();
        jButton1 = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Realizar Ejercicio");
        setToolTipText("");

        lblTit.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        lblDescri.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        lblReloj.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblReloj.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        txtItemEjer.setEditable(false);
        txtItemEjer.setBackground(new java.awt.Color(204, 204, 204));
        txtItemEjer.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtItemEjer.setForeground(new java.awt.Color(0, 0, 51));
        jScrollPane1.setViewportView(txtItemEjer);

        jButton1.setText("Finalizar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addComponent(lblDescri, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblTit, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblReloj, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(lblTit, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblDescri, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 7, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblReloj, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            if (ejercicio.getEjePpm() == 0) {
                Query q = entityManager.createQuery("SELECT t FROM Test t WHERE t.ejeCodigo = :ejeCodigo").setParameter("ejeCodigo", ejercicio);
                if (q.getResultList().isEmpty()) {
                    JOptionPane.showMessageDialog(null, "No existe test asignado para este ejercicio");
                } else {
                    JOptionPane.showMessageDialog(null, "Velocidad de lectura calculada: " + calculaVelocidad().toString() + "ppm");
                    Test testObj = (Test) q.getSingleResult();
                    RealizarTest e = new RealizarTest(testObj, calculaVelocidad());
                    LecturaMDI.desktopPane.add(e);
                    e.setVisible(true);
                    e.setMaximum(true);
                }
            }
        } catch (PropertyVetoException ex) {
            Logger.getLogger(MenuTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager entityManager;
    private java.util.List<entidades.ItemEjercicio> itemEjercicioList;
    private javax.persistence.Query itemEjercicioQuery;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblDescri;
    private javax.swing.JLabel lblReloj;
    private javax.swing.JLabel lblTit;
    private javax.swing.JTextPane txtItemEjer;
    // End of variables declaration//GEN-END:variables

    private void ejecutarEjercicio() {
        itemEjercicioQuery = entityManager.createQuery("SELECT i FROM ItemEjercicio i where i.ejeCodigo.ejeCodigo = :ejerCod order by i.iejOrden asc").setParameter("ejerCod", ejercicio.getEjeCodigo());
        itemEjercicioList = itemEjercicioQuery.getResultList();
        this.indice = 0;
        this.segundos = 0;
        this.minudos = 0;
        Timer timer = new Timer();
        if (ejercicio.getEjePpm() > 0) {
            String texto = itemEjercicioList.get(0).getIejTexto();
            Integer nroPal = new StringTokenizer(texto).countTokens();
            Integer velPpm = ejercicio.getEjePpm();
            Integer tiemItemEjer = nroPal * 60000 / velPpm;
            timer.schedule(new navegar(), 0, tiemItemEjer);
        } else {
            timer.schedule(new navegar(), 0, 1000 * 60 * 60 * 24);
        }
        timer.schedule(new reloj(), 0, 1000);
    }

    private Integer calculaVelocidad() {
        Integer seg;
        Double min, vel;
        seg = this.minudos * 60 + this.segundos;
        min = seg.doubleValue() / 60;
        Integer totalPalabras = new StringTokenizer(textoDeEjercicio).countTokens();
        vel = totalPalabras / min;
        return vel.intValue();
    }

    class navegar extends TimerTask {

        @Override
        public void run() {
            StyleContext context = new StyleContext();
            StyledDocument document = new DefaultStyledDocument(context);
            Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
            StyleConstants.setAlignment(style, StyleConstants.ALIGN_CENTER);

            String texto = itemEjercicioList.get(indice).getIejTexto();
            textoDeEjercicio = texto;
            try {
                document.insertString(document.getLength(), texto, style);
            } catch (BadLocationException ex) {
                Logger.getLogger(RealizarEjercicio.class.getName()).log(Level.SEVERE, null, ex);
            }

            txtItemEjer.setStyledDocument(document);
            indice++;
            if (indice >= itemEjercicioList.size()) {
                indice = 0;
            }
        }
    }

    class reloj extends TimerTask {

        @Override
        public void run() {
            lblReloj.setText(String.valueOf(minudos) + ":" + String.valueOf(segundos));
            if (segundos++ >= 59) {
                minudos++;
                segundos = 0;
            }
        }
    }
}
